// components/search.js
Component({
  properties: {
    btnText: String,
    navUrl: String,
    placeholder: String,
    dbName: String,
    refreshing: Number,
  },
  data: {
    searchText: '',
    // 预约日期区间
    start_date: '',
    end_date: '',
  },
  lifetimes: {
    attached() {
      this.initAppointment(); // 预约的初始化
    }
  },
  methods: {
    onChange(e) {
      this.setData({ searchText: e.detail });
    },
    onSearch() {
      if (this.data.dbName == 'tb_appointment') {
        console.log('搜索了');
        // 构造搜索 json string
        const searchObj = {
          searchText: this.data.searchText,
          dateRange: [this.data.start_date, this.data.end_date]
        }
        this.triggerEvent('search', { searchText: JSON.stringify(searchObj) });
      } else {
        this.triggerEvent('search', { searchText: this.data.searchText });
      }
    },
    onNavigate() {
      wx.navigateTo({
        url: this.data.navUrl,
      })
    },
    // 预约模块
    initAppointment() {
      const dayMsec = 86400 * 1000;
      const curMsec = parseInt(new Date() / dayMsec) * dayMsec - 8 * 3600 * 1000;
      const dateRange = [
        new Date(curMsec - 7 * dayMsec).Format('yyyy-MM-dd'),
        new Date(curMsec + 7 * dayMsec).Format('yyyy-MM-dd')
      ]
      this.setData({ start_date: dateRange[0], end_date: dateRange[1] })
    },
    onChangeDate(ev) {
      const dateStr = ev.detail.value;
      if (ev.currentTarget.dataset.date == 'start_date') {
        this.setData({ start_date: dateStr });
      }
      if (ev.currentTarget.dataset.date == 'end_date' || dateStr > this.data.end_date) {
        this.setData({ end_date: dateStr });
      }
      this.onSearch();
    }
  },
  observers: {
    'refreshing': function () {
      this.onSearch();
    }
  }
})
